<template>
    <div id="paraTree" class="paraTree" >
        <ul :id="treeId" class="ztree" :class="{'allHeight': config.title==''&&config.addBtn=='', titleHT: config.title!=''||config.addBtn!=''}"></ul>
    </div>
</template>

<script>
import $ from 'jquery';
import bus from '@/components/common/js/bus';
export default {
    name: 'tree',
    components:{  },
    props: {
        treeData: {
            type: Array,
            default() {
                return []
            }
        },
        config: {
            type: Object,
            default() {
                return {
                    btns: ['add', 'edit', 'delete'],
                    addBtn: '',
                    title: '',
                    pIdKey:'pId'
                }
            }
        },
        edit: {
            type: Boolean,
            default: true
        }
    },
    data() {
        return{
            treeId: 'treeDemo' + new Date().getTime(),
            setting: {
                view: {
                    addHoverDom: this.edit && this.addHoverDom,
                    showIcon: false,
                    showLine: true,
                    selectedMulti: false
                },
                edit: {
                    enable: this.edit,
                    showRemoveBtn: this.showRemoveBtn,
                    showRenameBtn: this.showRenameBtn,
                    removeTitle: '删除',
                    renameTitle: '修改',
                    drag: {
                        autoExpandTrigger: true,
                        prev: this.dropPrev,
                        inner: this.dropInner,
                        next: this.dropNext
                    },
                },
                data: {
                    simpleData: {
                        enable: true,
                        idKey: "id",
                        pIdKey: this.config.pIdKey,
                        rootPId: 0
                    }
                },
                callback: {
                    onClick: this.zTreeOnClick,
                    beforeDrag: this.beforeDrag,
                    beforeDrop: this.beforeDrop,
                    beforeDragOpen: this.beforeDragOpen,
                    onDrag: this.onDrag,
                    onDrop: this.onDrop,
                    onExpand: this.onExpand,
                    beforeEditName: this.beforeEditName,
                    beforeRename: this.beforeRename,
                    onRename: this.onRename,
                    beforeRemove: this.beforeRemove,
                    onRemove: this.onRemove,
                }
            },
            zNodes: [],
            log: '',
            className: 'dark',
            newCount: 1,
            curDragNodes: '',
            autoExpandNode: ''
        }
    },
    methods:{
        zTreeOnClick(event, treeId, treeNode) {
            // console.log('treeNode: ', treeNode);
            let allNodes = this.getAllNodes(); // 将当前树data传出去 供下次操作当作元数据
            this.$emit('treeNodeClick',treeNode, allNodes);
        },
        dropPrev(treeId, nodes, targetNode) {
			var pNode = targetNode.getParentNode();
			if (pNode && pNode.dropInner === false) {
				return false;
			} else {
				for (var i=0,l=this.curDragNodes.length; i<l; i++) {
					var curPNode = this.curDragNodes[i].getParentNode();
					if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
						return false;
					}
				}
			}
			return true;
        },
        dropInner(treeId, nodes, targetNode) {
			if (targetNode && targetNode.dropInner === false) {
				return false;
			} else {
				for (var i=0,l=this.curDragNodes.length; i<l; i++) {
					if (!targetNode && this.curDragNodes[i].dropRoot === false) {
						return false;
					} else if (this.curDragNodes[i].parentTId && this.curDragNodes[i].getParentNode() !== targetNode && this.curDragNodes[i].getParentNode().childOuter === false) {
						return false;
					}
				}
			}
			return true;
        },
        dropNext(treeId, nodes, targetNode) {
			var pNode = targetNode.getParentNode();
			if (pNode && pNode.dropInner === false) {
				return false;
			} else {
				for (var i=0,l=this.curDragNodes.length; i<l; i++) {
					var curPNode = this.curDragNodes[i].getParentNode();
					if (curPNode && curPNode !== targetNode.getParentNode() && curPNode.childOuter === false) {
						return false;
					}
				}
			}
			return true;
        },
        beforeDrag(treeId, treeNodes) {
			this.className = (this.className === "dark" ? "":"dark");
			this.showLog("[ "+this.getTime()+" beforeDrag ]&nbsp;&nbsp;&nbsp;&nbsp; drag: " + treeNodes.length + " nodes." );
			for (var i=0,l=treeNodes.length; i<l; i++) {
				if (treeNodes[i].drag === false) {
					this.curDragNodes = null;
					return false;
				} else if (treeNodes[i].parentTId && treeNodes[i].getParentNode().childDrag === false) {
					this.curDragNodes = null;
					return false;
				}
			}
			this.curDragNodes = treeNodes;
			return true;
        },
        beforeDragOpen(treeId, treeNode) {
			this.autoExpandNode = treeNode;
			return true;
        },
        beforeDrop(treeId, treeNodes, targetNode, moveType, isCopy) {
			this.className = (this.className === "dark" ? "":"dark");
			this.showLog("[ "+this.getTime()+" beforeDrop ]&nbsp;&nbsp;&nbsp;&nbsp; moveType:" + moveType);
			this.showLog("target: " + (targetNode ? targetNode.name : "root") + "  -- is "+ (isCopy==null? "cancel" : isCopy ? "copy" : "move"));
			return true;
        },
        onDrag(event, treeId, treeNodes) {
			this.className = (this.className === "dark" ? "":"dark");
			this.showLog("[ "+this.getTime()+" onDrag ]&nbsp;&nbsp;&nbsp;&nbsp; drag: " + treeNodes.length + " nodes." );
        },
        onDrop(event, treeId, treeNodes, targetNode, moveType, isCopy) {
			this.className = (this.className === "dark" ? "":"dark");
			this.showLog("[ "+this.getTime()+" onDrop ]&nbsp;&nbsp;&nbsp;&nbsp; moveType:" + moveType);
            this.showLog("target: " + (targetNode ? targetNode.name : "root") + "  -- is "+ (isCopy==null? "cancel" : isCopy ? "copy" : "move"));
        },
        onExpand(event, treeId, treeNode) {
            let allNodes = this.getAllNodes();
            this.$emit('treeNodeClick', treeNode, allNodes);
			if (treeNode === this.autoExpandNode) {
				this.className = (this.className === "dark" ? "":"dark");
				this.showLog("[ "+this.getTime()+" onExpand ]&nbsp;&nbsp;&nbsp;&nbsp;" + treeNode.name);
			}
        },
        remove() { // 移除节点
			var zTree = $.fn.zTree.getZTreeObj(this.treeId),
            nodes = zTree.getSelectedNodes(),
            treeNode = nodes[0];
            this.$emit("delTreeNode",treeNode)
		},
        beforeRemove(treeId, treeNode) {
            this.$emit("delTreeNode",treeNode);
            return false
        },
        beforeEditName(treeId, treeNode) {
            this.$emit('openParaType', treeNode, 'edit');
            return false
        },
        showLog(str) {
			if (!this.log) this.log = $("#log");
			this.log.append("<li class='"+this.className+"'>"+str+"</li>");
			if(this.log.children("li").length > 8) {
				this.log.get(0).removeChild(this.log.children("li")[0]);
			}
        },
        getTime() {
			var now= new Date(),
			h=now.getHours(),
			m=now.getMinutes(),
			s=now.getSeconds(),
			ms=now.getMilliseconds();
			return (h+":"+m+":"+s+ " " +ms);
        },

        addHoverDom(treeId, treeNode) {
            let _this = this;
            if (!treeNode.showAdd) return
			var sObj = $("#" + treeNode.tId + "_span");
			if (treeNode.editNameFlag || $("#addBtn_"+treeNode.tId).length>0) return;
			var addStr = "<span class='button add' id='addBtn_" + treeNode.tId
				+ "' title='新增' onfocus='this.blur();'></span>";
			sObj.after(addStr);
			var btn = $("#addBtn_"+treeNode.tId);
			if (btn) btn.bind("click", function(){
                if(treeNode.level == 1) _this.$emit('openParaType', treeNode, 'add'); // 添加参数分类
				return false;
			});
		},
        showRemoveBtn(treeId, treeNode){
            return treeNode.level == 2 && treeNode.edit
        },
        showRenameBtn(treeId, treeNode){
            return treeNode.level == 2 && treeNode.edit
        },
        getAllNodes() {
            var zTree = $.fn.zTree.getZTreeObj(this.treeId);
            var node = zTree.getNodes();
            return node
        },
    },
    watch: {
        treeData(val) {
            $.fn.zTree.init($("#" + this.treeId), this.setting, val);
            var zTree = $.fn.zTree.getZTreeObj(this.treeId);
        },
    },
    mounted() {
        $.fn.zTree.init($("#" + this.treeId), this.setting, this.treeData);
    },
}
</script>
<style lang="scss">
.paraTree{
    position: relative;
    height: 100%;
    background: #fff;
    .ztree{
        height: calc(100% - 30px);
        padding: 5px;
        li span.button.add{
            background-position: -143px 0;
        }
    }
    .allHeight {height: 100% !important;}
    .titleHT{height: calc(100% - 28px);}
    [treenode_a]{
        .button.add{
            display: none;
        }
        &:hover{
            .button.add{
                display: inline-block;
            }
        }
        span{
            vertical-align: middle !important;
        }
    }
    [treenode_a].curSelectedNode{
        .button.add{
            display: inline-block;
        }
    }
    [treenode_switch]{vertical-align: middle;}
}
</style>